package com.baijia.ticket;

import com.baijia.authentication.Authentication;
import com.baijia.authentication.principal.Service;

import org.springframework.util.Assert;
/**
 * @title ServiceTicketImpl
 * @desc nothing to say
 * @author caoliang
 * @date 2015年12月5日
 * @version 1.0
 */
public final class ServiceTicketImpl extends AbstractTicket implements
    ServiceTicket {

    private static final long serialVersionUID = -4223319704861765405L;

    /** ST需要校验的service */
    private Service service;

    private boolean fromNewLogin;

    private Boolean grantedTicketAlready = false;
    
    /** ST 超时时间 */
    private static final int EXPIRE_TIME = 100;
    
    public ServiceTicketImpl() {
        // exists for JPA purposes
    }

    protected ServiceTicketImpl(final String id,
        final TicketGrantingTicketImpl ticket, final Service service,
        final boolean fromNewLogin) {
        super(id, ticket);

        Assert.notNull(ticket, "ticket cannot be null");
        Assert.notNull(service, "service cannot be null");

        this.service = service;
        this.fromNewLogin = fromNewLogin;
    }

    @Override
    public boolean isFromNewLogin() {
        return this.fromNewLogin;
    }

    @Override
    public Service getService() {
        return this.service;
    }

    @Override
    public boolean isValidFor(final Service serviceToValidate) {
        updateState();
        return serviceToValidate.matches(this.service);
    }

    @Override
    public TicketGrantingTicket grantTicketGrantingTicket(
        final String id, final Authentication authentication) {
        synchronized (this) {
            if(this.grantedTicketAlready) {
                throw new IllegalStateException(
                    "TicketGrantingTicket already generated for this ServiceTicket.  Cannot grant more than one TGT for ServiceTicket");
            }
            this.grantedTicketAlready = true;
        }

        return new TicketGrantingTicketImpl(id, (TicketGrantingTicketImpl) this.getGrantingTicket(),
            authentication);
    }
    
    @Override
    public Authentication getAuthentication() {
        return null;
    }
    
    @Override
    public final boolean equals(final Object object) {
        if (object == null
            || !(object instanceof ServiceTicket)) {
            return false;
        }

        final Ticket serviceTicket = (Ticket) object;
        
        return serviceTicket.getId().equals(this.getId());
    }

    @Override
    public int getExpireTime() {
        return EXPIRE_TIME;
    }

    @Override
    public int getRememberMeExpireTimeExpireTime() {
        return 0;
    }
}
